package com.lz.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.gmall.common.execption.GmallException;
import com.lz.gmall.common.result.ResultCodeEnum;
import com.lz.gmall.constant.GmallConstant;
import com.lz.gmall.user.dto.UserLoginDto;
import com.lz.gmall.user.entity.UserInfo;
import com.lz.gmall.user.service.UserInfoService;
import com.lz.gmall.user.mapper.UserInfoMapper;
import com.lz.gmall.user.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 用户登录的校验
     * @param userLoginDto 登录信息
     * @return
     */
    @Override
    public UserLoginVo checkUserLogin(UserLoginDto userLoginDto) {

        String loginName = userLoginDto.getLoginName();


        //根据用户名进行查询
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getLoginName,loginName);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        //没有该用户
        if (userInfo==null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }
        //数据库中的密码是进行加密的，需要先加密再进行比较
        String passwd = userLoginDto.getPasswd();
        String loginPasswd = DigestUtils.md5DigestAsHex(passwd.getBytes());
        //密码不正确
        if (!userInfo.getPasswd().equalsIgnoreCase(loginPasswd)){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }

        //有该用户，密码正确，生成uuid（令牌）
        String token = UUID.randomUUID().toString().replace("-", "");
        //存入redis中
        redisTemplate.opsForValue().set(GmallConstant.REDIS_USER_LOGIN_TOKEN+token, JSON.toJSONString(userInfo));

        //封装数据
        UserLoginVo userLoginVo = new UserLoginVo();
        userLoginVo.setToken(token);
        userLoginVo.setNickName(loginName);
        return userLoginVo;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(GmallConstant.REDIS_USER_LOGIN_TOKEN+token);
    }
}




